package com.csot.ry.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.csot.common.constant.HttpStatus;
import com.csot.common.utils.StringUtils;
import com.csot.ry.domain.TCitySegment;
import com.csot.ry.poi.ExcelUtilSub;
import com.csot.ry.util.CacheKitUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.csot.common.annotation.Log;
import com.csot.common.core.controller.BaseController;
import com.csot.common.core.domain.AjaxResult;
import com.csot.common.enums.BusinessType;
import com.csot.ry.domain.TDcnSegment;
import com.csot.ry.service.ITDcnSegmentService;
import com.csot.common.utils.poi.ExcelUtil;
import com.csot.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * DCNController
 *
 * @author csot
 * @date 2023-04-03
 */
@RestController
@RequestMapping("/ipmanagement/dcn")
public class TDcnSegmentController extends BaseController
{
    @Autowired
    private ITDcnSegmentService tDcnSegmentService;

    /**
     * 查询DCN列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:dcn:list')")
    @GetMapping("/list")
    public TableDataInfo list(TDcnSegment tDcnSegment)
    {
        try {
            startPage();
            List<TDcnSegment> list = tDcnSegmentService.selectTDcnSegmentList(tDcnSegment);
            return getDataTable(list);
        } catch (Exception e) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg(StringUtils.isNotEmpty(e.getMessage()) ? "请联系管理员：" + e.getMessage() : "查询失败，请联系管理员");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
    }

    /**
     * 导出DCN列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:dcn:export')")
    @Log(title = "DCN", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TDcnSegment tDcnSegment)
    {
        String parentId = getLoginUser().getUser().getDept().getParentId() + "";
        if (CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId) && !"0".equals(parentId)) {
            tDcnSegment.setIpCity(CacheKitUtil.ip_dept.get(parentId + ""));
        }
        List<TDcnSegment> list = tDcnSegmentService.selectTDcnSegmentList(tDcnSegment);
        for (TDcnSegment t : list) {
            t.setIpUseType(CacheKitUtil.dcn_use_type.get(t.getIpUseType()));
            t.setIpCity(CacheKitUtil.ip_city.get(t.getIpCity()));
            t.setDeviceType(CacheKitUtil.device_type.get(t.getDeviceType()));
            t.setIpStatus(CacheKitUtil.dcn_use_status.get(t.getIpStatus()));
        }
        ExcelUtil<TDcnSegment> util = new ExcelUtil<TDcnSegment>(TDcnSegment.class);
        util.exportExcel(response, list, "DCN数据");
    }

    @Log(title = "Dcn导入", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('ipmanagement:dcn:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtilSub<TDcnSegment> util = new ExcelUtilSub<TDcnSegment>(TDcnSegment.class);
        List<TDcnSegment> tDcnSegmentList = util.importExcel(file.getInputStream());
        return toAjax(tDcnSegmentService.importDcnSegment(tDcnSegmentList));
    }
    @Log(title = "Dcn导入修改", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('ipmanagement:dcn:import')")
    @PostMapping("/importDataEdit")
    public AjaxResult importDataEdit(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtilSub<TDcnSegment> util = new ExcelUtilSub<TDcnSegment>(TDcnSegment.class);
        List<TDcnSegment> tCitySegmentList = util.importExcel(file.getInputStream());
        return toAjax(tDcnSegmentService.importEdit(tCitySegmentList));
    }

    //下载导入模板
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            String path = System.getProperty("user.dir");
            path = path + File.separator + "Template" + File.separator + "dcnTemplate.xlsx";
            IOUtils.write(Files.readAllBytes(Paths.get(path)), response.getOutputStream());
        } catch (IOException e) {
            logger.error("下载dcn模块异常", e);
        }
    }

    /**
     * 获取DCN详细信息
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:dcn:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tDcnSegmentService.selectTDcnSegmentById(id));
    }

    /**
     * 新增DCN
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:dcn:add')")
    @Log(title = "DCN", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TDcnSegment tDcnSegment)
    {
        return toAjax(tDcnSegmentService.insertTDcnSegment(tDcnSegment));
    }

    /**
     * 修改DCN
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:dcn:edit')")
    @Log(title = "DCN", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TDcnSegment tDcnSegment)
    {
        return toAjax(tDcnSegmentService.updateTDcnSegment(tDcnSegment));
    }

    /**
     * 删除DCN
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:dcn:remove')")
    @Log(title = "DCN", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tDcnSegmentService.deleteTDcnSegmentByIds(ids));
    }
}
